package com.siyoumi.app.modules.prize.service;

import com.siyoumi.app.entity.SysPrizeSet;
import com.siyoumi.app.entity.SysPrizeSetChou;
import com.siyoumi.app.entity.SysStock;
import com.siyoumi.app.modules.prize.entity.EnumPrizeType;
import com.siyoumi.app.modules.prize.vo.VaSysPrizeSet;
import com.siyoumi.app.service.SysPrizeSetChouService;
import com.siyoumi.app.service.SysPrizeSetService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.IEnum;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import java.util.*;

@Service
public class SvcSysPrizeSet {
    static public SvcSysPrizeSet getBean() {
        return XSpringContext.getBean(SvcSysPrizeSet.class);
    }

    static public SysPrizeSetService getApp() {
        return SysPrizeSetService.getBean();
    }

    static public Boolean isAct() {
        return XHttpContext.getAppId().equals("act");
    }


    public void editAfter(InputData inputData, XReturn r, String idSrc, boolean setChou) {
        Map<String, Object> data = new HashMap<>();
        data.put("pset_app_id", XHttpContext.getAppId());
        data.put("pset_type", "");
        data.put("pset_use_type", 2);
        data.put("pset_id_src", idSrc);
        data.put("pset_int_00", 0);
        data.put("pset_int_01", 0);
        data.put("pschou_win_rate", 0);
        data.put("pset_vaild_date_type", 1);
        data.put("pset_vaild_date_win_h", 0);
        data.put("pset_key", XApp.getStrID());
        //// 为了避免，错误修改，库存会赋到新值
        //data.put("__stock_count_use", 0);
        //data.put("__stock_count_left", 0);
        //data.put("__stock_count_left_old", 0);
        // 通知
        data.put("pset_send_type", 0);
        if (inputData.isAdminEdit()) {
            SysPrizeSet entity = getEntityByIdSrc(idSrc);
            data = entity.toMap();

            Map<String, Object> dataAppend = new LinkedHashMap<>();
            dataAppend.put("id", entity.getKey());

            //SysStock entityStock = SysStockService.getBean().getEntityBySrc(entity.getKey(), false);
            //if (entityStock != null) {
            //    dataAppend.put("__stock_count_use", entityStock.getStock_count_use());
            //    dataAppend.put("__stock_count_left", entityStock.getStock_count_left());
            //    dataAppend.put("__stock_count_left_old", entityStock.getStock_count_left());
            //}
            if (setChou) {
                SysPrizeSetChou entityPrizeChou = SysPrizeSetChouService.getBean().getEntity(entity.getKey());
                if (entityPrizeChou != null) {
                    dataAppend.putAll(entityPrizeChou.toMap());
                }
            }
            //合并
            data.putAll(dataAppend);
        }
        r.setData("data", data);


        Map<String, Object> mapPageInfo = r.getData("page_info");

        //奖品类型
        LinkedHashMap<String, String> prizeType = IEnum.toMap(EnumPrizeType.class);
        mapPageInfo.put("list_type", prizeType);
        mapPageInfo.put("is_wxapp", XHttpContext.getXConfig().wxApp());
    }

    /**
     * 保存验证
     *
     * @param result
     * @param vo
     */
    public void editSaveValidator(BindingResult result, VaSysPrizeSet vo) {
        if ("obj".equals(vo.getPset_type())) {
            switch (vo.getPset_use_type()) {
                case 0: //密码核销
                    if (XStr.isNullOrEmpty(vo.getPset_use_str_00())) {
                        result.addError(XValidator.getErr("pset_use_str_00", "请输入核销密码"));
                    }
                    break;
                case 1: //表单核销
                    break;
            }
        }
    }

    /**
     * 发奖配置-保存
     *
     * @param idSrc
     * @param vo
     */
    @SneakyThrows
    public void editSave(String idSrc, String appId, Object vo) {
        VaSysPrizeSet prizeSetVo = (VaSysPrizeSet) vo;
        //发奖配置
        SysPrizeSet entityPrizeSetSrc = getEntityByIdSrc(idSrc);
        SysPrizeSet entityPrizeSet = getApp().loadEntity(XBean.toMap(prizeSetVo));
        if (entityPrizeSetSrc == null) {
            entityPrizeSet.setPset_x_id(XHttpContext.getX());
            entityPrizeSet.setPset_app_id(appId);
            entityPrizeSet.setPset_id_src(idSrc);
            entityPrizeSet.setAutoID();
        }
        getApp().saveOrUpdatePassEqualField(entityPrizeSetSrc, entityPrizeSet);
    }

    public SysPrizeSet getEntityByIdSrc(String idSrc) {
        InputData inputData = InputData.getIns();
        inputData.put("id_src", idSrc);
        JoinWrapperPlus<SysPrizeSet> query = listQuery(inputData);

        return getApp().first(query);
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<SysPrizeSet> listQuery(InputData inputData) {
        String name = inputData.input("name");
        String idSrc = inputData.input("id_src");

        JoinWrapperPlus<SysPrizeSet> query = SvcSysPrizeSet.getApp().join();
        query.leftJoin(SysStock.table(), "stock_id_src", "pset_id");
        query.leftJoin(SysPrizeSetChou.table(), "pschou_id", "pset_id");

        query.eq("pset_x_id", XHttpContext.getX())
                .eq("pset_del", 0)
                .orderByAsc("pset_order")
                .orderByDesc("pset_id");
        if (XStr.hasAnyText(name)) { // 名称
            query.like("pset_name", name);
        }
        if (XStr.hasAnyText(idSrc)) {
            query.eq("pset_id_src", idSrc);
        }

        return query;
    }


    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        XReturn r = XReturn.getR(0);

        InputData inputData = InputData.getIns();
        JoinWrapperPlus<SysPrizeSet> query = listQuery(inputData);
        query.in("pset_id", ids);

        List<SysPrizeSet> list = getApp().get(query);
        for (SysPrizeSet entity : list) {
            getApp().delete(entity.getKey());
        }

        return r;
    }
}
